// 引入 QCloud 小程序增强 SDK
var qcloud = require('../../vendor/qcloud-weapp-client-sdk/index');
const util = require('../../utils/util.js');

// 引入配置
var config = require('../../config');

// 显示繁忙提示
var showBusy = text => wx.showToast({
    title: text,
    icon: 'loading',
    duration: 10000
});

// 显示成功提示
var showSuccess = text => wx.showToast({
    title: text,
    icon: 'success'
});

// 显示失败提示
var showModel = (title, content) => {
    wx.hideToast();

    wx.showModal({
        title,
        content: JSON.stringify(content),
        showCancel: false
    });
};

Page({
    /**
     * 初始数据，我们把服务地址显示在页面上
     */
    data: {
        latitude: 0,
        longitude: 0,
        message: {},
        content: '',
        localFiles: [],
        enabelSubmit: false,
        locationTitle: '',
        uploadedFiles: [],
        isSubmit : false,
        uploadFileUrl: config.service.uploadFileUrl,
        submitMessageUrl: config.service.submitMessageUrl,
        showChooseImageError: false
    },
    /**
     * 
     */
    onLoad(options) {
        // 加载的时候执行登录逻辑
        this.data.latitude = wx.getStorageSync('latitude');
        this.data.longitude = wx.getStorageSync('longitude');


    },
    onShow() {

        this.data.locationTitle = wx.getStorageSync('locationTitle');
        this.setData({
            locationTitle: this.data.locationTitle
        });
    },
    /**
     * 文字内容变化的时候触发
     */
    contentFocus(event) {
        this.data.enabelSubmit = true;
        this.setData({
            enabelSubmit: true
        });
    },
    // contentBlur(event) {
    //     this.data.isBlurContent = true;
    //     this.data.isFocusContent = false;
    //     var content = event.detail.value;
    //     this.data.content = content;
    //     var ebableSubmit;
    //     if (content.length > 0) {
    //         ebableSubmit = true;
    //     } else {
    //         ebableSubmit = false;
    //     }
    //     this.setData({
    //         enabelSubmit: ebableSubmit
    //     });

    //     if (this.data.isClickSubmit) {
    //         this.doSubmit();
    //     }
    // },
    inputContent(event) {
        this.data.content = event.detail.value;

    },
    /**
     * 选中图片
     */
    doChooseImage() {
        var that = this;
        var totalFileNum = 9;
        var allowUploadFileNum = totalFileNum - that.data.localFiles.length;
        wx.chooseImage({
            count: allowUploadFileNum, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                var tempFilePaths = res.tempFilePaths
                var localFiles = that.data.localFiles.concat(tempFilePaths); // 合并数组
                that.setData({
                    localFiles: localFiles,
                    content: that.data.content
                });
            }
        })
    },
    /**
     * 删除图片
     */
    doRemoveFile(e) {
        var that = this;
        var localFiles = that.data.localFiles;
        var obj = e.currentTarget;
        var index = obj.dataset.index;
        if (index >= 0) {
            localFiles.splice(index, 1);
            that.setData({
                localFiles: localFiles
            });
        }
    },
    /**
     * 点击位置描述
     */
    doChooseAddress() {
        showBusy("获取当前位置");
        var latitude;
        var longitude;
        wx.getLocation({
            type: 'wgs84',
            success: function (res) {
                latitude = res.latitude;
                longitude = res.longitude;
                wx.setStorageSync('latitude', latitude);
                wx.setStorageSync('longitude', longitude);
            },
            complete: function () {
                // showSuccess('获取位置成功');
                // 打开address列表界面
                wx.navigateTo({
                    url: "../address/index?latitude=" + latitude + "&longitude=" + longitude
                });
            }
        })
    },
    hideChooseImageError() {
        this.data.showChooseImageError = false;
        this.setData({
            showChooseImageError: false
        });
    },
    /**
     * 提交动态消息
     */
    doSubmit() {
        var that = this;

        // 检查内容，是否可以提交
        if (this.data.localFiles.length == 0) {
            this.data.showChooseImageError = true;
            this.setData({
                showChooseImageError: true
            });
            setTimeout(function () {
                that.hideChooseImageError();
            }, 2500);
            return;
        }
        // 消息内容，文件数组，地理位置
        showBusy("准备提交");

        if(this.data.isSubmit){
            return;
        }
        this.data.isSubmit = true;
        this.setData({
            isSubmit: this.data.isSubmit
        });

        // upload file
        var that = this;
        var doUploadFile = util.wxPromisify(wx.uploadFile);

        that.data.uploadedFiles = [];

        // 检查是否可以提交
        // if (that.data.content.length > 0) {}
        // do submit
        // 依次上传图片，获取图片的ID，然后在post数据
        var filePaths = that.data.localFiles;
        if (filePaths.length > 0) {
            showBusy("开始上传图片");
        }

        var promises = filePaths.map(function (filePath) {
            var index = 0;
            for (let i = 0; i < filePaths.length; i++) {
                if (filePath == filePaths[i]) {
                    index = i;
                    break;
                }
            }
            return doUploadFile({
                url: that.data.uploadFileUrl,
                filePath: filePath,
                name: 'wxFile',
                formData: {},
                method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
                header: { "Content-Type": "multipart/form-data" }
            }).then(function (res) {
                if (res.statusCode == 200) {
                    var ret = JSON.parse(res.data);
                    var qiniuUrl = ret.qiniuUrl;
                    // var fileUrl = data.data;
                    // uploadedFilse.push(fileUrl);
                    var obj = { index: index, qiniuUrl: qiniuUrl };
                    that.data.uploadedFiles.push(obj);
                    // showBusy("上传完第" + index + "图片");
                }
            }).catch(function () {
                console.error("get location failed")
            });
        });


        util.Promise.all(promises).then(function (posts) {
            // submit data
            // api.message.add(data, function (state, res) {
            //     console.log("state:" + state + "| res:" + res);
            // });
            var data = {
                content: that.data.content,
                uploadedFiles: that.data.uploadedFiles,
                latitude: that.data.latitude,
                longitude: that.data.longitude,
                locationTitle: that.data.locationTitle,
            };
            showBusy("提交动态信息");
            qcloud.request({
                // 要请求的地址
                url: that.data.submitMessageUrl,
                data: data,
                method: 'POST',
                // 请求之前是否登陆，如果该项指定为 true，会在请求之前进行登录
                login: true,
                success(result) {
                    showSuccess('提交动态成功');
                    console.log('request success', result);

                    // 发布成功，返回首页，并且首页刷新
                    wx.setStorageSync('homeNeedRefresh', true);
                    wx.navigateBack({
                        delta: 1, // 回退前 delta(默认为1) 页面
                        success: function (res) {
                            // success
                        },
                        fail: function () {
                            // fail
                        },
                        complete: function () {
                            // complete
                        }
                    })


                },
                fail(error) {
                    showModel('请求失败', error);
                    console.log('request fail', error);
                },
                complete() {
                    console.log('request complete');
                }
            });

        }).catch(function (reason) {
            console.log("files upload error");
        });
    }


});